package com.cicc.beergamevirtualsimulationsystem.common.webSocket.holder;

import com.cicc.beergamevirtualsimulationsystem.common.webSocket.config.WebSocketMessageSender;
import com.cicc.beergamevirtualsimulationsystem.common.webSocket.message.Impl.PlayerCountJsonWebSocketMessage;

import lombok.extern.slf4j.Slf4j;
import org.springframework.web.socket.WebSocketSession;

import java.util.HashSet;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.ConcurrentHashMap;

@Slf4j
public final class WebSocketSessionHolder {
    private WebSocketSessionHolder() {
    }

    private static final Map<String, Set<WebSocketSession>> sessionsByRoom = new ConcurrentHashMap<>();
//    private static final Map<String, webSocketEntity> sessionsByRoom = new ConcurrentHashMap<>();


    //添加session到对应房间
    public static void addSession(String roomId, WebSocketSession session) {
        sessionsByRoom.computeIfAbsent(roomId, k -> new HashSet<>()).add(session);

        //log.info("新的连接: " + session + " for room: " + roomId);
        //发广播更新当前房间人数
        WebSocketMessageSender.sendMessageToRoom(roomId,new PlayerCountJsonWebSocketMessage("当前房间人数："+sessionsByRoom.get(roomId).size()));

    }
    //移除session
    public static void removeSession(String roomId, WebSocketSession session) {
        Set<WebSocketSession> sessions = sessionsByRoom.get(roomId);
        if (sessions != null) {
            sessions.remove(session);
         //log.info("连接关闭: " + session + " for room: " + roomId);
            WebSocketMessageSender.sendMessageToRoom(roomId,new PlayerCountJsonWebSocketMessage("当前房间人数："+sessionsByRoom.get(roomId).size()));
//            WebSocketMessageSender.sendMessageToRoom(roomId, "当前房间人数：" + sessionsByRoom.get(roomId).size());
            if (sessions.isEmpty()) {
                sessionsByRoom.remove(roomId); // 如果没有更多会话，则移除房间条目
            }
        }
    }

    //获取对应房间的所有session
    public static Set<WebSocketSession> getSessionsByRoom(String roomId) {
        return sessionsByRoom.get(roomId);
    }

    //获取到对应的session
    public static WebSocketSession getSession(String roomId, String userId) {
        Set<WebSocketSession> sessions = sessionsByRoom.get(roomId);
        if (sessions != null) {
            for (WebSocketSession session : sessions) {
                if (session.getAttributes().get("userId").equals(userId)) {
                    return session;
                }
            }
        }
        return null;

    }
}
